package cn.edu.zjicm.wordsnet_d.view;

import android.app.Activity;
import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import cn.edu.zjicm.wordsnet_d.R;
import cn.edu.zjicm.wordsnet_d.data.MobclickAgentData;
import cn.edu.zjicm.wordsnet_d.data.StudyPlan;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference;
import cn.edu.zjicm.wordsnet_d.datapersistent.AppPreference.BookType;
import cn.edu.zjicm.wordsnet_d.db.WordFactory;
import cn.edu.zjicm.wordsnet_d.util.DateTimeUtils;
import cn.edu.zjicm.wordsnet_d.util.ShareUtil;
import cn.edu.zjicm.wordsnet_d.util.Utils;

public class ShareDialog {

	private String shareContent;
	private String shareTitle;
	private String shareTargetUrl;
	private Bitmap shareBitmap;
	private String imageURL;

	private Activity context;
	private View v;
	private Dialog dialog;
	private ImageView[] shareImg = new ImageView[5];
	private Button cancelButton;
	private TextView dialogTitle;
	private int rank = 0;

	private Utils.shareFrom shareFrom;
	// private Animation anim;
	private int animIndex;

	private WordFactory wf;

	public ShareDialog(Activity context, Utils.shareFrom shareFrom) {
		this.context = context;
		this.shareFrom = shareFrom;
		wf = WordFactory.getInstance(context);
		findViews();
		init();
		clickFunction();
	}

	public ShareDialog(Activity context, Utils.shareFrom shareFrom, int rank) {
		this.context = context;
		this.shareFrom = shareFrom;
		this.rank = rank;
		wf = WordFactory.getInstance(context);
		findViews();
		init();
		clickFunction();
	}

	public void clickFunction() {
		dialog = new Dialog(context, R.style.animation_for_share_dialog);// 这里应用了你的自定义样式
		dialog.setCanceledOnTouchOutside(true);
		v.setMinimumWidth(Utils.getScreenWidth(context));
		WindowManager.LayoutParams layoutParams = dialog.getWindow().getAttributes();
		layoutParams.x = 0;
		final int cMakeBottom = -1000;
		layoutParams.y = cMakeBottom;
		layoutParams.gravity = Gravity.BOTTOM;
		dialog.onWindowAttributesChanged(layoutParams);
		dialog.setContentView(v);
		dialog.show();
	}

	void findViews() {
		v = View.inflate(context, R.layout.view_share, null);
		shareImg[0] = (ImageView) v.findViewById(R.id.share_weixin);
		shareImg[1] = (ImageView) v.findViewById(R.id.share_friend);
		shareImg[2] = (ImageView) v.findViewById(R.id.share_qq);
		shareImg[3] = (ImageView) v.findViewById(R.id.share_qq_zone);
		shareImg[4] = (ImageView) v.findViewById(R.id.share_sina);

		cancelButton = (Button) v.findViewById(R.id.share_cancel);
		dialogTitle = (TextView) v.findViewById(R.id.share_dialog_title);
		startAnim();
	}

	private void startAnim() {
		for (int i = 0; i < shareImg.length; i++) {
			shareImg[i].setVisibility(View.INVISIBLE);
		}
		animIndex = 0;
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (animIndex < shareImg.length) {
					playAnimHandler.sendEmptyMessage(0);
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();

	}

	private void animation() {
		if (animIndex < shareImg.length) {
			shareImg[animIndex].startAnimation(AnimationUtils.loadAnimation(context, R.anim.rotate_bounce_up));
			shareImg[animIndex].setVisibility(View.VISIBLE);
			animIndex++;
		}
	}

	void init() {
		if (shareFrom == Utils.shareFrom.leardboardtab1) {
			dialogTitle.setText("分享你的打卡榜，让大家一起来比拼");
		} else if (shareFrom == Utils.shareFrom.leardboardtab2) {
			dialogTitle.setText("分享你的排名，让大家一起来比拼");
		} else if (shareFrom == Utils.shareFrom.leardboardtab3) {
			dialogTitle.setText("分享你的学校榜，让大家一起来比拼");
		}
		if ((shareFrom == Utils.shareFrom.leardboardtab1 || shareFrom == Utils.shareFrom.leardboardtab2) && rank == 0) {
			dialogTitle.setVisibility(View.INVISIBLE);
			v.findViewById(R.id.share_tablelayout).setVisibility(View.GONE);
			v.findViewById(R.id.show_text).setVisibility(View.VISIBLE);
			cancelButton.setText("好的");
		} else {
			for (int i = 0; i < shareImg.length; i++) {
				shareImg[i].setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						clickListener(v);
					}
				});
			}
		}
		cancelButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});

	}

	void clickListener(View v) {
		Utils.shareWay way = null;
		if (v == shareImg[0]) {// 微信
			way = Utils.shareWay.wechat;
		} else if (v == shareImg[1]) {// 微信朋友圈
			way = Utils.shareWay.wechatTimeline;
		} else if (v == shareImg[2]) {// qq
			way = Utils.shareWay.QQ;
		} else if (v == shareImg[3]) {// qq空间
			way = Utils.shareWay.QZone;
		} else if (v == shareImg[4]) {// sina
			way = Utils.shareWay.weibo;
		}
		initShareContent(way);
		new ShareUtil(context, way, shareBitmap, imageURL, shareTitle, shareContent, shareTargetUrl);
		dialog.cancel();
	}

	private void initShareContent(Utils.shareWay shareWay) {
		shareTitle = "知米背单词";
		shareTargetUrl = "http://www.iwordnet.com/mobile/circle.htm";
		shareBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.share_logo);
		imageURL = "http://www.iwordnet.com/mobile/image/share_logo.jpg";

		StringBuilder studyingBook = new StringBuilder();
		if (StudyPlan.isLearningWordBook(context)) {
			studyingBook.append(WordFactory.getInstance(context).getBookName(AppPreference.Book.BOOK_ID[AppPreference.getWordBookIndex(context)]));
		}
		if (StudyPlan.isLearningPhraseBook(context)) {
			if (studyingBook.length() > 0)
				studyingBook.append("和");

			studyingBook.append(WordFactory.getInstance(context).getBookName(AppPreference.Book.BOOK_ID[AppPreference.getPhraseBookIndex(context)]));
		}

		switch (shareFrom) {
		case mainActivity:
			shareTargetUrl = "http://www.iwordnet.com/mobile/m.circle.php";
			shareTargetUrl = getURL(shareTargetUrl);

			shareContent = "我正在学习" + studyingBook.toString() + "，已学" + getLearnedWords() + "个单词，我们一起刷单词吧！";
			switch (shareWay) {
			case weibo:
				MobclickAgentData.share(context, "主页分享--微博");
				String randomContent[] = { "以前我总是记不住单词，绝望是那么的触手可及，但是现在，我是傲视一切的单词小英雄，我感觉人生巅峰已离我不远了。你也想吗，那就一起背单词吧。", "我背单词从来都不是为了炫耀，我只希望自己能徜徉在英文经典的海洋，漫步在异国他乡的街头，让自己的心得到升华。我们一起背单词吧。",
						"我一直在坚持，只为心中的梦想，I am a slow walker，but I never walk backwards ，fighting! ", "The first step is as good as half over。第一步是最关键的一步，迈出了关键的一步，就已经成功了一半！我们一起背单词吧。" };
				shareTargetUrl = "http://t.cn/RzZc3Tt";
				shareContent = "我正在使用#知米背单词#学习" + studyingBook.toString() + "，已学" + getLearnedWords() + "个单词。" + randomContent[(int) (Math.random() * randomContent.length)] + "@知米英语";
				shareBitmap = Utils.getBitmapFromView(new CreateShareBitmap(context, Utils.createBitmapMode.forMainActivity).getView(), context);
				break;
			case QQ:
				MobclickAgentData.share(context, "主页分享--QQ");
				shareContent = "我正在学习" + studyingBook.toString() + "，已学" + getLearnedWords() + "个单词，等你来挑战！";

				break;
			case QZone:
				MobclickAgentData.share(context, "主页分享--QQ空间");
				shareContent = "我正在学习" + studyingBook.toString() + "，已学" + getLearnedWords() + "个单词，等你来挑战！";

				break;
			case wechat:
				MobclickAgentData.share(context, "主页分享--微信");
				break;
			case wechatTimeline:
				MobclickAgentData.share(context, "主页分享--微信朋友圈");
				break;
			}
			break;
		case slideMenu:
			shareTargetUrl = "http://www.iwordnet.com/word.php";
			shareContent = "知米背单词很好用，背单词轻松高效，很容易坚持，推荐使用。";
			switch (shareWay) {
			case weibo:
				MobclickAgentData.share(context, "侧滑分享--微博");
				shareTargetUrl = "http://t.cn/RzZc3Tt";
				String randomContent[] = { "以前我总是记不住单词，绝望是那么的触手可及，但是现在，我是傲视一切的单词小英雄，我感觉人生巅峰已离我不远了。你也想吗，那就一起背单词吧。", "我背单词从来都不是为了炫耀，我只希望自己能徜徉在英文经典的海洋，漫步在异国他乡的街头，让自己的心得到升华。我们一起背单词吧。",
						"我一直在坚持，只为心中的梦想，I am a slow walker，but I never walk backwards ，fighting! ", "The first step is as good as half over。第一步是最关键的一步，迈出了关键的一步，就已经成功了一半！我们一起背单词吧。" };
				shareContent = "我正在使用#知米背单词#，很好用哦，背单词轻松高效，很容易坚持。" + randomContent[(int) (Math.random() * randomContent.length)] + "@知米英语";
				shareBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.share_ad_weibo);
				break;
			case QQ:
				MobclickAgentData.share(context, "侧滑分享--QQ");
				break;
			case QZone:
				MobclickAgentData.share(context, "侧滑分享--QQ空间");
				imageURL = "http://www.iwordnet.com/mobile/image/share_ad_weibo.jpg";
				break;
			case wechat:
				MobclickAgentData.share(context, "侧滑分享--微信");
				break;
			case wechatTimeline:
				MobclickAgentData.share(context, "侧滑分享--微信朋友圈");
				break;
			}
			break;
		case leardboardtab1:
			shareTargetUrl = "http://www.iwordnet.com/mobile/share/daka.php";
			shareTargetUrl = getURL(shareTargetUrl);
			shareTitle = "知米背单词校园排行榜";
			shareContent = "我在" + AppPreference.getSchoolName(context) + "的打卡排名第" + rank + "位，我们一起刷单词吧！";
			switch (shareWay) {
			case weibo:
				MobclickAgentData.share(context, "排行榜分享_打卡榜--微博");
				shareTargetUrl = "http://t.cn/RzZc3Tt";
				if (rank < 4) {
					shareContent = "我正在使用#知米背单词#学习" + studyingBook.toString() + "，今天我在#知米背单词校园排行榜#之#" + AppPreference.getSchoolName(context) + "#的打卡排名第" + rank + "位，欢迎大家来围观拍砖！@知米英语";
				} else if (rank < 11) {
					shareContent = "我正在使用#知米背单词#学习" + studyingBook.toString() + "，今天我在#知米背单词校园排行榜#之#" + AppPreference.getSchoolName(context) + "#的打卡排名第" + rank
							+ "位，Victory won't come to me unless I go to it。胜利是不会向我们走来的，我必须自己走向胜利。@知米英语";
				} else {
					shareContent = "我正在使用#知米背单词#学习" + studyingBook.toString() + "，今天我在#知米背单词校园排行榜#之#" + AppPreference.getSchoolName(context) + "#的打卡排名第" + rank
							+ "位，Cease to struggle and you cease to live。生命不止，奋斗不息。@知米英语";
				}
				shareBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.share_ad_weibo);
				break;
			case QQ:
				shareContent = "我在" + AppPreference.getSchoolName(context) + "的打卡排名第" + rank + "位，等你来挑战！";
				MobclickAgentData.share(context, "排行榜分享_打卡榜--QQ");
				break;
			case QZone:
				shareContent = "我在" + AppPreference.getSchoolName(context) + "的打卡排名第" + rank + "位，等你来挑战！";
				imageURL = "http://www.iwordnet.com/mobile/image/share_ad_weibo.jpg";
				MobclickAgentData.share(context, "排行榜分享_打卡榜--QQ空间");
				break;
			case wechat:
				MobclickAgentData.share(context, "排行榜分享_打卡榜--微信");
				break;
			case wechatTimeline:
				MobclickAgentData.share(context, "排行榜分享_打卡榜--微信朋友圈");
				break;
			}
			break;
		case leardboardtab2:
			shareTargetUrl = "http://www.iwordnet.com/mobile/share/danci.php";
			shareTargetUrl = getURL(shareTargetUrl);
			shareTitle = "知米背单词校园排行榜";
			shareContent = "我在" + AppPreference.getSchoolName(context) + "的单词学习排名第" + rank + "位，我们一起刷单词吧！";
			switch (shareWay) {
			case weibo:
				MobclickAgentData.share(context, "排行榜分享_单词学习榜--微博");
				shareTargetUrl = "http://t.cn/RzZc3Tt";
				if (rank < 4) {
					shareContent = "我正在使用#知米背单词#学习" + studyingBook.toString() + "，今天我在#知米背单词校园排行榜#之#" + AppPreference.getSchoolName(context) + "#的打卡排名第" + rank + "位，欢迎大家来围观拍砖！@知米英语";
				} else if (rank < 11) {
					shareContent = "我正在使用#知米背单词#学习" + studyingBook.toString() + "，今天我在#知米背单词校园排行榜#之#" + AppPreference.getSchoolName(context) + "#的打卡排名第" + rank
							+ "位，Victory won't come to me unless I go to it。胜利是不会向我们走来的，我必须自己走向胜利。@知米英语";
				} else {
					shareContent = "我正在使用#知米背单词#学习" + studyingBook.toString() + "，今天我在#知米背单词校园排行榜#之#" + AppPreference.getSchoolName(context) + "#的打卡排名第" + rank
							+ "位，Cease to struggle and you cease to live。生命不止，奋斗不息。@知米英语";
				}
				shareBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.share_ad_weibo);
				break;
			case QQ:
				shareContent = "我在" + AppPreference.getSchoolName(context) + "的单词学习排名第" + rank + "位，等你来挑战！";
				MobclickAgentData.share(context, "排行榜分享_单词学习榜--QQ");
				break;
			case QZone:
				shareContent = "我在" + AppPreference.getSchoolName(context) + "的单词学习排名第" + rank + "位，等你来挑战！";
				imageURL = "http://www.iwordnet.com/mobile/image/share_ad_weibo.jpg";
				MobclickAgentData.share(context, "排行榜分享_单词学习榜--QQ空间");
				break;
			case wechat:
				MobclickAgentData.share(context, "排行榜分享_单词学习榜--微信");
				break;
			case wechatTimeline:
				MobclickAgentData.share(context, "排行榜分享_单词学习榜--微信朋友圈");
				break;
			}
			break;
		case leardboardtab3:
			shareTargetUrl = "http://www.iwordnet.com/mobile/share/xuexiao.php";
			shareTargetUrl = getURL(shareTargetUrl);
			shareTitle = "知米背单词校园排行榜";
			shareContent = AppPreference.getSchoolName(context) + "在所有学校排行中第" + rank + "位，同校的伙伴们，来贡献你的力量吧！";
			switch (shareWay) {
			case weibo:
				MobclickAgentData.share(context, "排行榜分享_学校榜--微博");
				shareTargetUrl = "http://t.cn/RzZc3Tt";
				shareContent = "我正在使用#知米背单词#学习" + studyingBook.toString() + "，我所在的#" + AppPreference.getSchoolName(context) + "#在#知米背单词校园排行榜#之中排名第" + rank + "位，同校的小伙伴们，来贡献你的力量吧！@知米英语";
				shareBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.share_ad_weibo);
				break;
			case QQ:
				MobclickAgentData.share(context, "排行榜分享_学校榜--QQ");
				break;
			case QZone:
				MobclickAgentData.share(context, "排行榜分享_学校榜--QQ空间");
				imageURL = "http://www.iwordnet.com/mobile/image/share_ad_weibo.jpg";
				break;
			case wechat:
				MobclickAgentData.share(context, "排行榜分享_学校榜--微信");
				break;
			case wechatTimeline:
				MobclickAgentData.share(context, "排行榜分享_学校榜--微信朋友圈");
				break;
			}
			break;
		}
	}

	private String getURL(String originalURL) {
		shareTargetUrl = originalURL;
		String nickname = AppPreference.getNickName(context);
		if (nickname == null) {
			nickname = AppPreference.getLoginID(context);
		}
		if (nickname.equals("guest") || nickname.equals("")) {
			nickname = "Guest";
		}

		int wordLeftDays = 0, phraseLeftDays = 0;
		int wordUnlearnCount = 0, phraseUnlearnCount = 0, wordAllCount = 0, phraseAllCount = 0;
		if (StudyPlan.isLearningWordBook(context)) {
			wordUnlearnCount = wf.getUnLearnedWordCount(AppPreference.getWordBookIndex(context));
			wordAllCount = wf.getWordCountInBook(AppPreference.getWordBookIndex(context));
			wordLeftDays = DateTimeUtils.getLeftDays(context, BookType.BOOK_WORD, wordUnlearnCount);
		}
		if (StudyPlan.isLearningPhraseBook(context)) {
			phraseUnlearnCount = wf.getUnLearnedWordCount(AppPreference.getPhraseBookIndex(context));
			phraseAllCount = wf.getWordCountInBook(AppPreference.getPhraseBookIndex(context));
			phraseLeftDays = DateTimeUtils.getLeftDays(context, BookType.BOOK_PHRASE, phraseUnlearnCount);
		}
		int degree = (wordAllCount + phraseAllCount - wordUnlearnCount - phraseUnlearnCount) / (wordAllCount + phraseAllCount) * 100;

		int unfamiliarWordsNum1 = 0;
		for (int i = 1; i <= WordFactory.wordReviewTime.length - 2; i++) {
			unfamiliarWordsNum1 += AppPreference.getNewWordsFmDegree(context, i);
		}
		int familiarWordsNum1 = AppPreference.getNewWordsFmDegree(context, WordFactory.wordReviewTime.length - 1);
		int unlearnedWordsNum1 = AppPreference.getNewWordsFmDegree(context, 0);

		shareTargetUrl += "?str=";
		shareTargetUrl += nickname;// 用户昵称
		shareTargetUrl += "%23";
		shareTargetUrl += (wordLeftDays + phraseLeftDays);// 距离完成计划剩余天数
		shareTargetUrl += "%23";
		shareTargetUrl += degree;// 中心圆圈的百分比
		shareTargetUrl += "%23";
		shareTargetUrl += unfamiliarWordsNum1;// 生词
		shareTargetUrl += "%23";
		shareTargetUrl += familiarWordsNum1;// 熟词
		shareTargetUrl += "%23";
		shareTargetUrl += unlearnedWordsNum1;// 未学单词
		shareTargetUrl += "%23";
		shareTargetUrl += AppPreference.getToken(context);// 用户唯一token
		shareTargetUrl += "%23";
		shareTargetUrl += rank;// 用户排名
		shareTargetUrl += "%23";
		shareTargetUrl += AppPreference.getSchoolName(context);// 用户所在学校
		shareTargetUrl += "%23";
		if (AppPreference.getHeadPortrait(context) == null) {
			shareTargetUrl += "0";// 用户没有设置头像
		} else {
			shareTargetUrl += "1";// 用户设置了头像
		}

		shareTargetUrl = Utils.changeCharsetToUTF8(shareTargetUrl);
		return shareTargetUrl;
		// LogUtil.e("分享的网址", shareTargetUrl);
	}

	private int getLearnedWords() {
		int nums = 0;
		for (int i = 2; i <= 7; i++) {
			nums += AppPreference.getNewWordsFmDegree(context, 8 - i);
		}
		return nums;
	}

	private Handler playAnimHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0)
				animation();
		}

	};

}
